﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace Demo_2D
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private COMPort comport = new COMPort();
        private DeviceInf device_inf = new DeviceInf();

        //通信设备
        private comInterface slave_dev; 

        //串口日志锁
        private Mutex log_process_mutex = new Mutex();
        //日志字符串
        private List<string> log_process_str = new List<string>();
        //界面更新定时器委托
        private DispatcherTimer UI_Timer;
        //串口接收日志定时器委托
        private DispatcherTimer Recv_Timer;

        //串口开启状态
        private bool com_is_open = false;

        static AnthorTagInf anthor_l = new AnthorTagInf("1", "null", "null", "null", string.Empty);
        static AnthorTagInf anthor_2 = new AnthorTagInf("2", "null", "null", "null", string.Empty);
        static AnthorTagInf anthor_3 = new AnthorTagInf("3", "null", "null", "null", string.Empty);
        static AnthorTagInf anthor_4 = new AnthorTagInf("4", "null", "null", "null", string.Empty);
        static AnthorTagInf tag_1 = new AnthorTagInf("标签坐标", "null", "null", "null", string.Empty);
        List<AnthorTagInf> anthorALL = new List< AnthorTagInf > { anthor_l, anthor_2, anthor_3, anthor_4, tag_1 };

        private void PassLogStr(string log)
        {
            if (log_process_mutex.WaitOne(5))
            {
                log_process_str.Add(log);
                log_process_mutex.ReleaseMutex();
            }
        }

        /// <summary>
        /// 初始化基站标签绑定数据结构
        /// </summary>
        private void InitAnthorTagDgrid()
        {
            ObservableCollection < AnthorTagInf > at_inf = new ObservableCollection<AnthorTagInf> (anthorALL);
            AnchorCoorDgrid.DataContext = at_inf;
        }

        /// <summary>
        /// 初始化各个UI界面
        /// </summary>
        private void InitUI()
        {
            //串口UI界面显示
            foreach (string port in comport.GetCOMPortList())
            {
                COMListcbox.Items.Add(port);
            }
            string temp = comport.GetDefaultPort();
            if (temp.Equals("null"))
            {
                MessageBox.Show("未找到可用串口，连接设备后重新打开软件！");
                System.Environment.Exit(0); //退出所有程序
            }
            COMListcbox.SelectedItem = temp;
            comport.SetCurrentCOMPort(temp);
            
            //串口参数设置
            comport.SetCurrentBaudRate("115200");
            comport.SetCurrentDataBit("8");
            comport.SetCurrentParityBit("None(无)");
            comport.SetCurrentStopBit("1");

            InitAnthorTagDgrid();
        }

        private void UI_Timer_Tick(object sender, EventArgs e)
        {
            if (log_process_mutex.WaitOne(5))
            {
                if (log_process_str.Count > 0)
                {
                    for (int i = 0; i < log_process_str.Count; i++)
                    {
                        ComportLogtext.AppendText(log_process_str[i]);
                    }
                    ComportLogtext.ScrollToEnd();
                    log_process_str.Clear();
                }
            }
            RecvDataShow_Tick();
        }

        /// <summary>
        /// 接收设备上发数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        //private void RecvDataShow_Tick(object sender, EventArgs e)
        private void RecvDataShow_Tick()
        {
            if (com_is_open)
            {
                //读取设备数据
                slave_dev.Read(out device_inf.rdat);

                //解析设备数据
                if (device_inf.ParseRecv())
                {
                    //填充显示长度数据
                    string temp = "数据帧序列号: " + device_inf.rpl[device_inf.rpl.Count - 1].fnum.ToString() + " \r\n";
                    temp += "基站一距离: " + device_inf.rpl[device_inf.rpl.Count - 1].l_1.ToString() + " cm\r\n";
                    temp += "基站二距离: " + device_inf.rpl[device_inf.rpl.Count - 1].l_2.ToString() + " cm\r\n";
                    temp += "基站三距离: " + device_inf.rpl[device_inf.rpl.Count - 1].l_3.ToString() + " cm\r\n";

                    PassLogStr(temp);
                }
            }
        }

        /// <summary>
        /// 初始化线程
        /// </summary>
        private void InitPthread()
        {
            UI_Timer = new DispatcherTimer();
            UI_Timer.Tick += new EventHandler(UI_Timer_Tick);
            UI_Timer.Interval = new TimeSpan(0, 0, 0, 0, 30);
            UI_Timer.Start();

            //Recv_Timer = new DispatcherTimer();
            //Recv_Timer.Tick += new EventHandler(RecvDataShow_Tick);
            //Recv_Timer.Interval = new TimeSpan(0, 0, 0, 30);
            //Recv_Timer.Start();
        }

        /// <summary>
        /// 主窗口程序
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();
            InitUI();
            InitPthread();
        }
        /// <summary>
        /// 主窗口退出释放所有资源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 打开串口按键事件操作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OpenCombut_Click(object sender, RoutedEventArgs e)
        {
            /**
            BitmapImage bi3 = new BitmapImage();
            bi3.BeginInit();
            bi3.UriSource = new Uri("E:\\zx-code\\demo-2D-pos\\Demo-2D\\Demo-2D\\Demo-2D\\bin\\Debug\\test.png", UriKind.Absolute);
            bi3.EndInit();
            ShowImage.Stretch = Stretch.Fill;
            ShowImage.Source = bi3;
            **/

            if (false == comport.IsOpen())
            {//打开设备操作
                comport.SetCurrentCOMPort(COMListcbox.SelectedItem.ToString());
                comport.OpenCOMPort();
                OpenCombut.Content = "关闭串口";
                COMListcbox.IsEnabled = false;

                //设备获取
                slave_dev = comport;

                com_is_open = true;
            }
            else
            {//关闭设备操作
                comport.CloseCOMPort();
                OpenCombut.Content = "打开串口";
                COMListcbox.IsEnabled = true;

                com_is_open = false;
            }
        }
    }
}
